<?php

class Poll extends BaseTopic implements iEditBody {
	public function prepare($page, $new, $item, $inputs) {	
		if ($new) {
			$inputs[] = $this->creator->input_select("Aantal antwoorden", "num_answers", array(2, 3, 4, 5, 6, 7), 
										  array("twee","drie","vier","vijf","zes","zeven"), 
										  "kies een getal", "", "document.itemform.submit()"); //TODO: extract javascript
		}
		
		if (!$new) { // get answer info
			$sql = $this->db_access->db_query_select(
					array(
							array("*")), 
					array("POLL_ANSWER"), 
					"item_id = {$this->id}");
			$sqlresult = $this->db_access->db_do_query($sql);
			$num_answers = $this->db_access->db_num_rows($sqlresult);
			while ($row = $this->db_access->db_fetch_array($sqlresult)) {
				$answers[] = $row;
			}
			$inputs[] = $this->creator->input_hidden("num_answers", $num_answers);
		}

		for ($i = 0; $i < ($new ? $_POST['num_answers'] : $num_answers); $i++) {
			if (!$new) {
				$inputs[] = $this->creator->input_hidden("answer_{$i}_id", $answers[$i]['answer_id']);
			}
			$inputs[] = $this->creator->input_field("Antwoord #" . ($i+1), "answer_{$i}", 
					$this->db_access->db_desqlize($answers[$i]['answer']));
		}
		
		$inputs[] = $this->creator->input_text(
				"Beschrijving vraag", 
				"body", 
				$this->db_access->db_desqlize($item['body']));
		return $inputs;
	}

	protected function derive_info() {
		$info = strip_tags($_POST['body']);
		return substr($info, 0, 50) . ((strlen($info) > 50) ? "&hellip;" : "");
	}

	public function get_edit_body() {
		$sql = $this->db_access->db_query_select(
				array(
						array('*')), 
				array("POLL"), 
				"item_id = {$this->id}");
		$sqlresult = $this->db_access->db_do_query($sql);
		$poll = $this->db_access->db_fetch_array($sqlresult);
		return $poll['body'];
	}

	public function check_content($values, $new) {
		$ok = $this->checker->check_tags_advanced($values['body'], "body");
		$ok = $ok && $this->checker->check_tag_closures($values['body']);
		return $ok && $this->checker->check_exists($values['body'], "body");
		for ($i = 0; $i < $values['num_answers']; $i++) {
			$ok = $this->checker->checkAnswer($ok, $values, $i);
		}
		return $ok;
	}

	protected function get_sql_from_post($item_id) {
		for ($i = 0; $i < $_POST['num_answers']; $i++) {
			$sql = $this->db_access->db_query_insert(
					array('item_id', 'answer'), 
					array(
							$item_id, 
							$this->db_access->db_sqlize($_POST["answer_$i"])), 
					"POLL_ANSWER");
			$this->db_access->db_do_query($sql);
		}
		return $this->db_access->db_query_insert(
				array('item_id', 'body'), 
				array(
						$item_id, 
						$this->db_access->db_sqlize($_POST['body'])), 
				"POLL");	
	}
}

?>
